package com.yuncheng.spcyApi.controller;

import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.yuncheng.spcyApi.vo.sj.PxDjExcelVo;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.other.PxSjConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.*;

import com.yuncheng.annotation.AutoLog;
import com.yuncheng.common.base.controller.BaseController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.vo.common.StartEndTimeVo;
import com.yuncheng.spcyApi.vo.sj.DjjbxxVo;
import com.yuncheng.spcyApi.vo.sj.DjtmVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-培训-答卷基本信息
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "审评查验-培训-答卷基本信息接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyPxDjjbxx")
public class SpcyPxDjjbxxController extends BaseController<SpcyPxDjjbxx, ISpcyPxDjjbxxService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyPxDjjbxxController.class);

    @Resource
    private ISpcyPxDjjbxxService spcyPxDjjbxxService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private ISpcyPxDjtmService spcyPxDjtmService;

    @Resource
    private ISpcyPxDjdaService spcyPxDjdaService;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private ISpcyPxJbxxService spcyPxJbxxService;

    /**
     * 分页列表查询
     *
     * @param spcyPxDjjbxx
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "答卷基本信息-分页列表查询")
    @ApiOperation(value = "答卷基本信息-分页列表查询")
    @GetMapping(value = "/djjbxxPageList")
    public HttpResult<?> djjbxxPageList(SpcyPxDjjbxx spcyPxDjjbxx,
                                        StartEndTimeVo startEndTimeVo,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcyPxDjjbxx> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcyPxDjjbxx> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFsjlx()),SpcyPxDjjbxx::getFsjlx,spcyPxDjjbxx.getFsjlx());
        queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFsjmc()),SpcyPxDjjbxx::getFsjmc,spcyPxDjjbxx.getFsjmc());
        queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFksxm()),SpcyPxDjjbxx::getFksxm,spcyPxDjjbxx.getFksxm());
        queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFgzdw()),SpcyPxDjjbxx::getFgzdw,spcyPxDjjbxx.getFgzdw());
        queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFlxdh()),SpcyPxDjjbxx::getFlxdh,spcyPxDjjbxx.getFlxdh());
        queryWrapper.like(StringUtils.isNotBlank(spcyPxDjjbxx.getFdf()),SpcyPxDjjbxx::getFdf,spcyPxDjjbxx.getFdf());
        if (startEndTimeVo.getStartTime() != null && startEndTimeVo.getEndTime() != null){
            queryWrapper.between(SpcyPxDjjbxx::getFtjsj,startEndTimeVo.getStartTime(),startEndTimeVo.getEndTime());
        }
        if (StringUtils.isNotBlank(startEndTimeVo.getFlag())) {
            if (startEndTimeVo.getFlag().equals("是")) {
                queryWrapper.isNotNull(SpcyPxDjjbxx::getFtjsj);
            } else {
                queryWrapper.isNull(SpcyPxDjjbxx::getFtjsj);
            }
        }

        // 2023-6-26 新增
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser != null) {
            if (!SpcyConstant.Org_Code_Admin.equals(currentUser.getDeptCode())){
                queryWrapper.eq(SpcyPxDjjbxx::getSysOrgCode, currentUser.getDeptCode());
            }
        }

        queryWrapper.orderByDesc(SpcyPxDjjbxx::getFtjsj);
        queryWrapper.orderByDesc(SpcyPxDjjbxx::getCreateTime);
        IPage<SpcyPxDjjbxx> pageList = spcyPxDjjbxxService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }



    /**
     * 添加
     *
     * @param spcyPxDjjbxx
     * @return
     */
    @AutoLog(value = "答卷基本信息-添加")
    @ApiOperation(value = "答卷基本信息-添加")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "fsjid",name = "试卷id",required = true),
            @ApiImplicitParam(value = "fksxm",name = "考试姓名",required = true),
            @ApiImplicitParam(value = "fgzdw",name = "工作单位",required = true),
            @ApiImplicitParam(value = "flxdh",name = "联系电话",required = true)
    })
    @PostMapping(value = "/addDjjbxx")
    public HttpResult<?> addDjjbxx(@RequestBody SpcyPxDjjbxx spcyPxDjjbxx) {
        if (StringUtils.isEmpty(spcyPxDjjbxx.getFsjid())){
            return HttpResult.error("试卷id不能为空");
        }
        if (StringUtils.isEmpty(spcyPxDjjbxx.getFksxm())){
            return HttpResult.error("考生姓名不能为空");
        }
        if (StringUtils.isEmpty(spcyPxDjjbxx.getFgzdw())){
            return HttpResult.error("单位名称不能为空");
        }
        if (StringUtils.isEmpty(spcyPxDjjbxx.getFlxdh())){
            return HttpResult.error("联系电话不能为空");
        }
        String ysjId = spcyPxDjjbxx.getFsjid();
        // 初始化-试卷
        spcyPxDjjbxxService.initDjjbxx(spcyPxDjjbxx,ysjId);

        return HttpResult.ok("添加成功");
    }

    /**
     * 编辑
     *
     * @return
     */
    @AutoLog(value = "答卷基本信息-编辑")
    @ApiOperation(value = "答卷基本信息-编辑")
    @ApiImplicitParam(name = "id",value = "答卷基本信息id",required = true)
    @PutMapping(value = "/editDjjbxx")
    public HttpResult<?> editDjjbxx(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("答卷基本信息id不能为空");
        }
        String djjxxxId = buffer.get("id");
        SpcyPxDjjbxx oldDjjbxx = spcyPxDjjbxxService.getById(djjxxxId);
        String sysOrgCode = oldDjjbxx.getSysOrgCode();
        SpcyPxDjjbxx oldDjjbxxUpdate = spcyPxDjjbxxService.getById(djjxxxId);
        if (oldDjjbxxUpdate == null){
            return HttpResult.error("当前答卷基本信息数据不存在，请重试");
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldDjjbxxUpdate, buffer);
        oldDjjbxxUpdate.setSysOrgCode(sysOrgCode);
        spcyPxDjjbxxService.updateById(oldDjjbxxUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldDjjbxx);
        operContent += LogUtils.BeanModifyMsg(oldDjjbxxUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_PX_DJJBXX,operContent,djjxxxId,LogConstant.LOGS_PX_DJJBXX,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "答卷基本信息-批量删除")
    @ApiOperation(value = "答卷基本信息-批量删除")
    @DeleteMapping(value = "/deleteBatchDjjbxx")
    public HttpResult<?> deleteBatchDjjbxx(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyPxDjjbxx> spcyPxDjjbxxList = spcyPxDjjbxxService.listByIds(idsList);
        if (CollectionUtils.isEmpty(spcyPxDjjbxxList)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcyPxDjjbxx djjbxx : spcyPxDjjbxxList){
            String djId = djjbxx.getId(); // 试卷id

            // 删除答卷题目 和 选项
            LambdaQueryWrapper<SpcyPxDjtm> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SpcyPxDjtm::getFdjid, djId);
            List<SpcyPxDjtm> sjtmList = spcyPxDjtmService.list(queryWrapper);

            spcyPxDjjbxxService.removeById(djId); // 删除答卷

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(djjbxx);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_PX_DJJBXX,operContent,djId,LogConstant.LOGS_PX_DJJBXX,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";

            // 不为空
            if (CollectionUtils.isNotEmpty(sjtmList)){
                for (SpcyPxDjtm sjtm : sjtmList){
                    String sjtmId = sjtm.getId();
                    spcyPxDjtmService.removeById(sjtm.getId()); // 删除答卷题目
                    spcyPxDjdaService.remove(new LambdaQueryWrapper<SpcyPxDjda>()
                            .eq(SpcyPxDjda::getFdjtmid, sjtmId)); // 删除答卷题目选项
                }
            }
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "答卷基本信息-通过id查询")
    @ApiOperation(value = "答卷基本信息-通过id查询")
    @GetMapping(value = "/queryDjjbxxById")
    public HttpResult<?> queryDjjbxxById(@RequestParam("id") String id) {
        SpcyPxDjjbxx spcyPxDjjbxx = spcyPxDjjbxxService.getById(id);
        return HttpResult.ok(spcyPxDjjbxx);
    }

    @AutoLog(value = "填写主观题")
    @ApiOperation(value = "填写主观题")
    @PostMapping(value = "updateDjtmZgt")
    public HttpResult<?> updateDjtmZgt(@RequestBody SpcyPxDjtm djtm){
        if (StringUtils.isBlank(djtm.getId())){
            return HttpResult.error("答卷题目参数不能为空");
        }
        SpcyPxDjtm updateDjtm = spcyPxDjtmService.getById(djtm.getId());
        if (updateDjtm == null){
            return HttpResult.error("当前题目不存在，请刷新重试");
        }
        String oldZgt = updateDjtm.getFzgtnr();
        updateDjtm.setFsfdd(PxSjConstant.SJTM_SFDD_YES);
        updateDjtm.setFzgtnr(djtm.getFzgtnr());
        boolean flag = spcyPxDjtmService.updateById(updateDjtm);
        if (flag) {
            String log = "填写题目主观题：【题目】->[" + updateDjtm.getFsjtm() + "];\n【主观题内容】: ["+oldZgt+"]->["+djtm.getFzgtnr()+"]";
            spcyLogService.addLogs(LogConstant.LOGS_PX_DJTM, log, djtm.getFdjid(), SpcyConstant.LOGS_SYS_TYPE_XG, SpcyConstant.LOGS_SYS_TYPE_XG);
        }else {
            return HttpResult.error("保存失败，请刷新重试，并联系管理员");
        }

        return HttpResult.ok("保存成功");
    }

//    @AutoLog(value = "答卷答案-编辑")
//    @ApiOperation(value = "答卷答案-编辑")
//    @ApiImplicitParam(name = "id",value = "答卷答案id",required = true)
//    @PutMapping(value = "/editDjda")
    public HttpResult<?> editDjda(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("答卷答案id不能为空");
        }
        String gcyId = buffer.get("id");
        SpcyPxDjda oldDjtm = spcyPxDjdaService.getById(gcyId);
        SpcyPxDjda oldDjtmUpdate = spcyPxDjdaService.getById(gcyId);
        if (oldDjtmUpdate == null){
            return HttpResult.error("当前答卷答案信息数据不存在，请重试");
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldDjtmUpdate, buffer);
        spcyPxDjdaService.updateById(oldDjtmUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldDjtm);
        operContent += LogUtils.BeanModifyMsg(oldDjtmUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_PX_DJDA,operContent,gcyId,LogConstant.LOGS_PX_DJDA,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    @AutoLog(value = "提交答卷")
    @ApiOperation(value = "提交答卷")
    @ApiImplicitParam(name = "id",value = "答卷id",required = true)
    @GetMapping(value = "submitDj")
    public HttpResult<?> submitDj(@RequestParam(value = "id",defaultValue = "")String djId){
        if (StringUtils.isEmpty(djId)){
            return HttpResult.error("答卷id不能为空");
        }

        // 是否同步培训基本信息
        boolean isSyncPxjbxx = false;

        SpcyPxDjjbxx dj = spcyPxDjjbxxService.getById(djId);
        if (dj == null){
            return HttpResult.error("答卷为空");
        }
        if (dj.getFtjsj() != null){
            return HttpResult.error("已经提交过答卷了,不能重复提交");
        }

        if (StringUtils.isNotBlank(dj.getFpxjbxxid()) && StringUtils.isNotBlank(dj.getFuserid())){
            isSyncPxjbxx = true;
        }

        String sysOrgCode = dj.getSysOrgCode();
        dj.setFtjsj(new Date());
        dj.setSysOrgCode(sysOrgCode);
        spcyPxDjjbxxService.updateById(dj);

        // 计算题目得分
        spcyPxDjjbxxService.JsDjTmScore(djId);

        // 计算总得分
        String df = spcyPxDjjbxxService.JsDjtmTotalScore(djId);

        // 同步培训基本信息
        if (isSyncPxjbxx) {
            spcyPxJbxxService.syncCjryKsxx(dj.getFpxjbxxid(), dj.getFuserid(), df);
        }

        return HttpResult.ok("提交成功");
    }

    @AutoLog(value = "验证提交答卷是否考试合格")
    @ApiOperation(value = "验证提交答卷是否考试合格")
    @ApiImplicitParam(name = "id",value = "答卷id",required = true)
    @GetMapping(value = "verifyDjhg")
    public HttpResult verifyDjhg(@RequestParam(value = "id",defaultValue = "")String djId){

//        String flag = "";

        SpcyPxDjjbxx dj = spcyPxDjjbxxService.getById(djId);
        if (dj == null){
            throw new BusinessException("没有相匹配的数据！");

        }else {

            // 计算题目得分
            spcyPxDjjbxxService.JsDjTmScore(djId);

            // 计算总得分
            String df = spcyPxDjjbxxService.JsDjtmTotalScore(djId);

            // 验证人员参加考试是否合格
            Map map = spcyPxJbxxService.verifyCjryKssfgf(dj.getFpxjbxxid(), dj.getFuserid(), df, dj.getFhgx());

            String sjzf = Optional.ofNullable(dj.getFdjzf()).orElseGet(()->"100");
            map.put("sjzf", sjzf);
            return HttpResult.ok(map);
        }

        /*Map resultMap = new HashMap();
        resultMap.put("flag", flag);
        return HttpResult.ok(resultMap);*/
    }

    /**
     * 通过id查询答卷详细信息
     */
    @AutoLog(value = "通过id查询答卷详细信息")
    @ApiOperation(value = "通过id查询答卷详细信息")
    @ApiImplicitParam(value = "id",name = "答卷id",required = true)
    @GetMapping(value = "/queryDjxqxxById")
    public HttpResult<?> queryDjxqxxById(@RequestParam("id")String id){
        if (StringUtils.isEmpty(id)){
            return HttpResult.error("答卷id不能为空");
        }
        DjjbxxVo djjbxxVo = new DjjbxxVo();

        SpcyPxDjjbxx djjbxx = spcyPxDjjbxxService.getById(id);
        djjbxxVo.setDjjbxx(djjbxx); // 存放答卷基本信息

        // 单选题
        List<SpcyPxDjtm> djtmDanxList = spcyPxDjtmService.list(new LambdaQueryWrapper<SpcyPxDjtm>()
                .eq(SpcyPxDjtm::getFdjid, id)
                .eq(SpcyPxDjtm::getFtmlx, PxSjConstant.SJTM_LX_DANX)
                .orderByAsc(SpcyPxDjtm::getFxh));

        List<DjtmVo> djtmVoList1 = new ArrayList<>(); // 存放答卷题目和选项
        List<SpcyPxDjda> djdaList1 = new ArrayList<>();
        // 单选题
        if (CollectionUtils.isNotEmpty(djtmDanxList)){
            for (SpcyPxDjtm djtm : djtmDanxList){
                DjtmVo djtmVo = new DjtmVo();
                BeanUtil.copyProperties(djtm,djtmVo); // 存放题目
                // 题目选项
                djdaList1 = spcyPxDjdaService.list(new LambdaQueryWrapper<SpcyPxDjda>()
                        .eq(SpcyPxDjda::getFdjtmid, djtm.getId())
                        .orderByAsc(SpcyPxDjda::getFxh));
                djtmVo.setDjdaList(djdaList1); // 存放答案选项
                djtmVoList1.add(djtmVo);
            }
        }

        // 多选题
        List<SpcyPxDjtm> djtmDuoxList = spcyPxDjtmService.list(new LambdaQueryWrapper<SpcyPxDjtm>()
                .eq(SpcyPxDjtm::getFdjid, id)
                .eq(SpcyPxDjtm::getFtmlx, PxSjConstant.SJTM_LX_DUOX)
                .orderByAsc(SpcyPxDjtm::getFxh));

        List<DjtmVo> djtmVoList2 = new ArrayList<>(); // 存放答卷题目和选项
        List<SpcyPxDjda> djdaList2 = new ArrayList<>();
        // 多选题
        if (CollectionUtils.isNotEmpty(djtmDuoxList)){
            for (SpcyPxDjtm djtm : djtmDuoxList){
                DjtmVo djtmVo = new DjtmVo();
                BeanUtil.copyProperties(djtm,djtmVo); // 存放题目
                // 题目选项
                djdaList2 = spcyPxDjdaService.list(new LambdaQueryWrapper<SpcyPxDjda>()
                        .eq(SpcyPxDjda::getFdjtmid, djtm.getId())
                        .orderByAsc(SpcyPxDjda::getFxh));
                djtmVo.setDjdaList(djdaList2); // 存放答案选项
                djtmVoList2.add(djtmVo);
            }
        }

        // 主观题
        List<SpcyPxDjtm> djtmZhugList = spcyPxDjtmService.list(new LambdaQueryWrapper<SpcyPxDjtm>()
                .eq(SpcyPxDjtm::getFdjid, id)
                .eq(SpcyPxDjtm::getFtmlx, PxSjConstant.SJTM_LX_ZHUG)
                .orderByAsc(SpcyPxDjtm::getFxh));

        List<DjtmVo> djtmVoList3 = new ArrayList<>(); // 存放答卷题目和选项
        List<SpcyPxDjda> djdaList3 = new ArrayList<>();
        // 主观题
        if (CollectionUtils.isNotEmpty(djtmZhugList)){
            for (SpcyPxDjtm djtm : djtmZhugList){
                DjtmVo djtmVo = new DjtmVo();
                BeanUtil.copyProperties(djtm,djtmVo); // 存放题目
                // 题目选项
                djdaList3 = spcyPxDjdaService.list(new LambdaQueryWrapper<SpcyPxDjda>()
                        .eq(SpcyPxDjda::getFdjtmid, djtm.getId())
                        .orderByAsc(SpcyPxDjda::getFxh));
                djtmVo.setDjdaList(djdaList3); // 存放答案选项
                djtmVoList3.add(djtmVo);
            }
        }

        // 判断题 // 2023-5-10 新增
        List<SpcyPxDjtm> pdtList = spcyPxDjtmService.list(new LambdaQueryWrapper<SpcyPxDjtm>()
                .eq(SpcyPxDjtm::getFdjid, id)
                .eq(SpcyPxDjtm::getFtmlx, PxSjConstant.SJTM_LX_PDT)
                .orderByAsc(SpcyPxDjtm::getFxh));

        List<DjtmVo> djtmVoPdtList1 = new ArrayList<>(); // 存放答卷题目和选项
        List<SpcyPxDjda> djdaPdtList1 = new ArrayList<>();
        // 判断题
        if (CollectionUtils.isNotEmpty(pdtList)){
            for (SpcyPxDjtm djtm : pdtList){
                DjtmVo djtmVo = new DjtmVo();
                BeanUtil.copyProperties(djtm,djtmVo); // 存放题目
                // 题目选项
                djdaPdtList1 = spcyPxDjdaService.list(new LambdaQueryWrapper<SpcyPxDjda>()
                        .eq(SpcyPxDjda::getFdjtmid, djtm.getId())
                        .orderByAsc(SpcyPxDjda::getFxh));
                djtmVo.setDjdaList(djdaPdtList1); // 存放答案选项
                djtmVoPdtList1.add(djtmVo);
            }
        }
        djjbxxVo.setDanxList(djtmVoList1);
        djjbxxVo.setDuoxList(djtmVoList2);
        djjbxxVo.setZhugList(djtmVoList3);

        djjbxxVo.setPdtList(djtmVoPdtList1); // 2023-5-10 新增
        return HttpResult.ok(djjbxxVo);
    }

    /**
     * 分享-提交考生信息
     * @param spcyPxDjjbxx
     * @return
     */
    @AutoLog(value = "分享-提交考生信息")
    @ApiOperation(value = "分享-提交考生信息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "fsjid",name = "试卷id",required = true),
            @ApiImplicitParam(value = "fksxm",name = "考试姓名",required = true),
            @ApiImplicitParam(value = "fgzdw",name = "工作单位",required = true),
            @ApiImplicitParam(value = "flxdh",name = "联系电话",required = true)
    })
    @PostMapping(value = "/submitDjjbxx")
    public HttpResult<?> submitDjjbxx(@RequestBody SpcyPxDjjbxx spcyPxDjjbxx) {
        if (StringUtils.isEmpty(spcyPxDjjbxx.getFsjid())){
            return HttpResult.error("试卷id不能为空");
        }
        if (StringUtils.isEmpty(spcyPxDjjbxx.getFksxm())){
            return HttpResult.error("考生姓名不能为空");
        }
        if (StringUtils.isEmpty(spcyPxDjjbxx.getFgzdw())){
            return HttpResult.error("单位名称不能为空");
        }
        if (StringUtils.isEmpty(spcyPxDjjbxx.getFlxdh())){
            return HttpResult.error("联系电话不能为空");
        }
        String ysjId = spcyPxDjjbxx.getFsjid();

        // 初始化-试卷
        String djId = spcyPxDjjbxxService.initDjjbxx(spcyPxDjjbxx, ysjId);

        // 以上复制试卷
        // 一下查询答卷详细

        Map map = new HashMap();
        map.put("id",djId);
        return HttpResult.ok(map);
    }

    /**
     * 分享-提交答卷信息
     */
//    @AutoLog(value = "分享-提交答卷信息")
//    @ApiOperation(value = "分享-提交答卷信息")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(value = "id",name = "答卷id",required = true),
//            @ApiImplicitParam(value = "djdaList",name = "答卷题目选项数组",required = true)
//    })
//    @PostMapping(value = "submitDjxx")
    public HttpResult<?> submitDjxx(@RequestBody Map map){

        String djId = map.get("id").toString();
        // 获取传过来的 所以选中的选项id
        List<SpcyPxDjda> djdaList = (List<SpcyPxDjda>) map.get("djdaList");

        if (StringUtils.isEmpty(djId)){
            return HttpResult.error("答卷id不能为空");
        }
        if (CollectionUtils.isEmpty(djdaList)){
            return HttpResult.error("提交失败，参数丢失");
        }
        for (SpcyPxDjda djda : djdaList){
            String djdaId = djda.getId();
            SpcyPxDjda nowDjda = spcyPxDjdaService.getById(djdaId);
            if (djda == null){
                continue;
            }
            nowDjda.setFsfxz(PxSjConstant.SJTM_DJDA_SFZQDA_YES); // 选中
            if (StringUtils.isNotBlank(djda.getFdjda())){
                nowDjda.setFdjda(djda.getFdjda()); // 答卷答案
            }
            spcyPxDjdaService.updateById(nowDjda);
        }
        SpcyPxDjjbxx djjbxx = spcyPxDjjbxxService.getById(djId);
        if (djjbxx != null) {
            djjbxx.setFtjsj(new Date());
            spcyPxDjjbxxService.updateById(djjbxx);
        }

        // 计算题目得分
        spcyPxDjjbxxService.JsDjTmScore(djId);

        return HttpResult.ok("提交成功");
    }

    /**
     * 答卷答案单选、多选选中
     */
    @AutoLog(value = "答卷答案单选、多选选中")
    @ApiOperation(value = "答卷答案单选、多选选中")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "id",name = "答案id",required = true),
            @ApiImplicitParam(value = "fdjtmid",name = "答卷题目id",required = true)
    })
    @GetMapping(value = "/selectDjDa")
    public HttpResult<?> selectDjDa(SpcyPxDjda djda){
        if (StringUtils.isBlank(djda.getId())){
            return HttpResult.error("答案id不能为空");
        }
        if (StringUtils.isBlank(djda.getFdjtmid())){
            return HttpResult.error("答卷题目id不能为空");
        }

        SpcyPxDjtm djtm = spcyPxDjtmService.getById(djda.getFdjtmid());
        if (djtm == null){
            return HttpResult.error("答卷题目不存在，请重试");
        }
        String ftmlx = djtm.getFtmlx();
        // 单选
        if (ftmlx.equals(PxSjConstant.SJTM_LX_DANX)){
            List<SpcyPxDjda> djdaList = spcyPxDjdaService.list(new LambdaQueryWrapper<SpcyPxDjda>()
                    .eq(SpcyPxDjda::getFdjtmid, djda.getFdjtmid()));
            if (CollectionUtils.isNotEmpty(djdaList)){
                for (SpcyPxDjda d : djdaList){
                    d.setFsfxz(PxSjConstant.SJTM_DJDA_SFXZ_NO); // 重置单选题-所以选中为否
                    spcyPxDjdaService.updateById(d);
                }
                SpcyPxDjda nowDjda = spcyPxDjdaService.getById(djda.getId());
                if (nowDjda != null){
                    nowDjda.setFsfxz(PxSjConstant.SJTM_DJDA_SFXZ_YES); // 选中 为是
                    spcyPxDjdaService.updateById(nowDjda);
                }
            }
        }

        // 多选
        if (ftmlx.equals(PxSjConstant.SJTM_LX_DUOX)){
            SpcyPxDjda nowDjda = spcyPxDjdaService.getById(djda.getId());
            if (nowDjda != null){
                nowDjda.setFsfxz(djda.getFsfxz());
                spcyPxDjdaService.updateById(nowDjda);
            }
        }

        // 判断 2023-5-10 新增
        if (ftmlx.equals(PxSjConstant.SJTM_LX_PDT)){
            List<SpcyPxDjda> djdaList = spcyPxDjdaService.list(new LambdaQueryWrapper<SpcyPxDjda>()
                    .eq(SpcyPxDjda::getFdjtmid, djda.getFdjtmid()));
            if (CollectionUtils.isNotEmpty(djdaList)){
                for (SpcyPxDjda d : djdaList){
                    d.setFsfxz(PxSjConstant.SJTM_DJDA_SFXZ_NO); // 重置单选题-所以选中为否
                    spcyPxDjdaService.updateById(d);
                }
                SpcyPxDjda nowDjda = spcyPxDjdaService.getById(djda.getId());
                if (nowDjda != null){
                    nowDjda.setFsfxz(PxSjConstant.SJTM_DJDA_SFXZ_YES); // 选中 为是
                    spcyPxDjdaService.updateById(nowDjda);
                }
            }
        }
        return HttpResult.ok("选中完成");
    }

    /**
     * 查询成绩-根据姓名和电话
     */
    @AutoLog(value = "查询成绩-根据姓名和电话")
    @ApiOperation(value = "查询成绩-根据姓名和电话")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "fksxm",name = "考试姓名",required = true),
            @ApiImplicitParam(value = "flxdh",name = "联系电话",required = true),
    })
    @GetMapping(value = "/queryCjByNameAndphone")
    public HttpResult<?> queryCjByNameAndphone(@RequestParam("flxdh")String flxdh,@RequestParam("fksxm")String fksxm){
        if (StringUtils.isBlank(fksxm)){
            return HttpResult.error("考试姓名不能为空");
        }
        if (StringUtils.isBlank(flxdh)){
            return HttpResult.error("联系电话不能为空");
        }
        LambdaQueryWrapper<SpcyPxDjjbxx> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcyPxDjjbxx::getFksxm,fksxm);
        queryWrapper.eq(SpcyPxDjjbxx::getFlxdh,flxdh);
        queryWrapper.isNotNull(SpcyPxDjjbxx::getFtjsj);
        List<SpcyPxDjjbxx> list = spcyPxDjjbxxService.list(queryWrapper);

        return HttpResult.ok(list);
    }

    /**
     * 导出答卷基本信息
     */
    @AutoLog(value = "导出答卷基本信息")
    @ApiOperation(value = "导出答卷基本信息")
    @GetMapping(value = "exportDjjbxxData")
    public void exportDjjbxxData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                SpcyPxDjjbxx spcyPxDjjbxx,
                                StartEndTimeVo startEndTimeVo,
                                HttpServletResponse response){
        try {
            String name = "exportPxDjjbxx";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            PxDjExcelVo excelVo = null;
            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcyPxDjjbxx> spcyPxDjjbxxList = spcyPxDjjbxxService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(spcyPxDjjbxxList)){
                    for (SpcyPxDjjbxx e : spcyPxDjjbxxList){
                        excelVo = new PxDjExcelVo();
                        try {
                            BeanUtil.copyProperties(e, excelVo);
                            list.add(excelVo);
                        }catch (Exception ex){
                            list.add(e);
                        }
                    }
                }
            }else {
                LambdaQueryWrapper<SpcyPxDjjbxx> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFsjlx()),SpcyPxDjjbxx::getFsjlx,spcyPxDjjbxx.getFsjlx());
                queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFsjmc()),SpcyPxDjjbxx::getFsjmc,spcyPxDjjbxx.getFsjmc());
                queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFksxm()),SpcyPxDjjbxx::getFksxm,spcyPxDjjbxx.getFksxm());
                queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFgzdw()),SpcyPxDjjbxx::getFgzdw,spcyPxDjjbxx.getFgzdw());
                queryWrapper.like(StringUtils.isNotEmpty(spcyPxDjjbxx.getFlxdh()),SpcyPxDjjbxx::getFlxdh,spcyPxDjjbxx.getFlxdh());
                queryWrapper.like(StringUtils.isNotBlank(spcyPxDjjbxx.getFdf()),SpcyPxDjjbxx::getFdf,spcyPxDjjbxx.getFdf());
                if (startEndTimeVo.getStartTime() != null && startEndTimeVo.getEndTime() != null){
                    queryWrapper.between(SpcyPxDjjbxx::getFtjsj,startEndTimeVo.getStartTime(),startEndTimeVo.getEndTime());
                }
                if (StringUtils.isNotBlank(startEndTimeVo.getFlag())) {
                    if (startEndTimeVo.getFlag().equals("是")) {
                        queryWrapper.isNotNull(SpcyPxDjjbxx::getFtjsj);
                    } else {
                        queryWrapper.isNull(SpcyPxDjjbxx::getFtjsj);
                    }
                }
                queryWrapper.orderByDesc(SpcyPxDjjbxx::getFtjsj);
                queryWrapper.orderByDesc(SpcyPxDjjbxx::getCreateTime);
                List<SpcyPxDjjbxx> spcyPxDjjbxxList = spcyPxDjjbxxService.list(queryWrapper);
                // 条件导出
                if (CollectionUtils.isNotEmpty(spcyPxDjjbxxList)){
                    for (SpcyPxDjjbxx e : spcyPxDjjbxxList){
                        excelVo = new PxDjExcelVo();
                        try {
                            BeanUtil.copyProperties(e, excelVo);
                            list.add(excelVo);
                        }catch (Exception ex){
                            list.add(e);
                        }
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_PX_DJJBXX_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出观察员数据出错-{}",e.getMessage());
        }
    }

}
